//
//  YTMineWebController.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/8/8.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "YTMineWebController.h"
#import <WebKit/WebKit.h>
@interface YTMineWebController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property(nonatomic ,strong)WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;

@property(nonatomic ,strong)WKWebViewConfiguration *config;
@end


@implementation YTMineWebController

// lazy progressView
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 0, kScreenWidth, 4);
        _progressView.trackTintColor = [UIColor clearColor]; // 设置进度条的色彩
        _progressView.progressTintColor = kMainColor;
        // 设置初始的进度，防止用户进来就懵逼了（微信大概也是一开始设置的10%的默认值）
        [_progressView setProgress:0.1 animated:YES];
    }
    return _progressView;
}

- (WKWebViewConfiguration *)config
{
    if (!_config) {
        _config = [[WKWebViewConfiguration alloc] init];
    }
    return _config;
}
// lazy webView
- (WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44) configuration:self.config];
       
        if (self.isActive) {
            _webView.navigationDelegate = self;
            _webView.UIDelegate = self;
            [[_webView configuration].userContentController addScriptMessageHandler:self name:@"sendImgUrl"];
        }

    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    if (self.shouldLogin) {
        [request setValue:YTNetworkManager.shareManager.account.auth forHTTPHeaderField:@"user-token"];
    }
    
    // 精彩活动附带参数
    if (self.isActive) {
        NSString *timescap = [NSString getNowTime];
        NSString *userToken = YTNetworkManager.shareManager.account.auth;
        [request setValue:userToken forHTTPHeaderField:@"user-token"];
        
        [request setValue:timescap forHTTPHeaderField:@"time"];
        
        NSString *sign = [[NSString stringWithFormat:@"%@%@%@",kGetVerifiCodeKey,timescap,userToken] md5];
        
        [request setValue:sign forHTTPHeaderField:@"sign"];
    }
    
    [self.webView loadRequest:request.copy];
 
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage dh_setNavImageName:@"倛袨1"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick)];
    
    // KVO，监听webView属性值得变化(estimatedProgress,title为特定的key)
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)dealloc {
    
    // 移除监听
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
}

// 返回按钮
- (void)backButtonClick
{
    if (self.webView.canGoBack) {
        [self.webView goBack];
        return;
    }
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - KVO监听
// 第三部：完成监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([object isEqual:self.webView] && [keyPath isEqualToString:@"estimatedProgress"]) { // 进度条
        
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        NSLog(@"打印测试进度值：%f", newprogress);
        
        if (newprogress == 1) { // 加载完成
            // 首先加载到头
            [self.progressView setProgress:newprogress animated:YES];
            // 之后0.3秒延迟隐藏
            __weak typeof(self) weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                
                weakSelf.progressView.hidden = YES;
                [weakSelf.progressView setProgress:0 animated:NO];
            });
            
        } else { // 加载中
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    } else if ([object isEqual:self.webView] && [keyPath isEqualToString:@"title"]) { // 标题
        
        //self.title = self.webView.title;
    } else { // 其他
        
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    // 平台首页
    if ([message.name isEqualToString:@"sendImgUrl"]) {
        //在分享按钮绑定如下触发代码
        //显示分享面板
        [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
            // 根据获取的platformType确定所选平台进行下一步操作
            NSLog(@"%@",userInfo);
            [self shareWebPageToPlatformType:platformType imgUrl:message.body];//新增代码
        }];
        
    }
    
    // 返回
    if ([message.name isEqualToString:@"sendClose"]) {
        [self.navigationController popViewControllerAnimated:true];
    }
}

//定义实现的方法
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType imgUrl:(NSString *)imgUrl
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    

    UMShareImageObject *shareOject = [[UMShareImageObject alloc] init];
    
    [shareOject setShareImage:imgUrl];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareOject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        NSLog(@"分享出错%@",error);//修改代码
    }];
}


@end
